
package com.gitee.jmash.oidc.oauth2.jaxrs;

import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import org.apache.commons.lang3.StringUtils;
import com.gitee.jmash.common.utils.BasicAuthzUtil;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.oidc.oauth2.enums.ScopeType;
import com.gitee.jmash.oidc.oauth2.models.ErrorResponse;
import com.gitee.jmash.oidc.oauth2.models.UserInfoModel;
import com.gitee.jmash.oidc.web.Constant;
import com.gitee.jmash.rbac.RbacFactory;
import com.gitee.jmash.rbac.entity.TokenEntity;
import com.gitee.jmash.rbac.entity.UserEntity;
import com.xyvcard.ops.OpsFactory;
import com.xyvcard.ops.entity.OpsClientEntity;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

/**
 * OpenId 获取用户属性.
 *
 * @author CGD
 *
 */
@Path("/userinfo")
public class UserInfoEndpoint {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response userInfoGet(@HeaderParam("Authorization") String authorization,
      @QueryParam("access_token") String accessToken) {
    return userInfo(authorization, accessToken);
  }

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  public Response userInfoPost(@HeaderParam("Authorization") String authorization,
      @FormParam("access_token") String accessToken) {
    return userInfo(authorization, accessToken);
  }

  /** OpenId Connect Userinfo Endpoint Implement. */
  public Response userInfo(String authorization, String accessToken) {
    // 1.验证Header Authorization Bearer.
    String[] creds = BasicAuthzUtil.decodeBasicAuthz(authorization);
    if (creds == null || creds.length != 2) {
      return ErrorResponse.createResponse("invalid_client", "Header Authorization Bearer Error.");
    }

    // 2.验证clientId、clientSecret
    OpsClientEntity client =
        OpsFactory.getOpsClientRead(Constant.TENANT).findBySecret(creds[0], creds[1]);
    if (client == null) {
      return ErrorResponse.createResponse("invalid_client", "client_id或client_Secret错误.");
    }

    // 3.获取认证信息
    TokenEntity token =
        RbacFactory.getUserRead(Constant.TENANT).findTokenByAccessToken(creds[0], accessToken);
    if (token == null) {
      return ErrorResponse.createResponse("invalid_request", "accessToken错误.");
    }
    UserEntity account = RbacFactory.getUserRead(Constant.TENANT).findById(token.getUserId());
    UserInfoModel userInfo = new UserInfoModel();
    userInfo.setSub(UUIDUtil.uuid32(account.getUserId()));
    // Scope profile
    if (StringUtils.contains(token.getScope(), ScopeType.profile.name())) {
      userInfo.setName(account.getLoginName());
      userInfo.setNickname(account.getNickName());
      userInfo.setPreferredUsername(account.getRealName());
      userInfo.setProfile("");
      userInfo.setPicture(account.getAvatar());
      userInfo.setWebsite("");
      userInfo.setGender(account.getGender());
      userInfo.setBirthdate(account.getBirthDate().format(DateTimeFormatter.ISO_LOCAL_DATE));
      userInfo.setUpdatedAt(account.getUpdateTime().toInstant(ZoneOffset.UTC));
    }
    // Scope email
    if (StringUtils.contains(token.getScope(), ScopeType.email.name())) {
      userInfo.setEmail(account.getEmail());
      userInfo.setEmailVerified(account.getEmailApproved());
    }
    // Scope phone
    if (StringUtils.contains(token.getScope(), ScopeType.phone.name())) {
      userInfo.setPhoneNumber(account.getMobilePhone());
      userInfo.setEmailVerified(account.getPhoneApproved());
    }
    // Scope address
    if (StringUtils.contains(token.getScope(), ScopeType.address.name())) {
      // ...
      //userInfo.setAddress(null);
    }
    return Response.ok().entity(userInfo).build();
  }

}
